<template>
  <div>
    <el-card>
      <!-- 搜索栏 -->
      <SearchForm
        :form-option="formOption"
        :show-btn="true"
        :btn-list="btnList"
        v-model="formOption.formData"
        label-width="90px"
      />

      <!-- 数据表格 start -->
      <PageTable
        :loading="loading"
        :data="dataSource"
        :columns="columns"
        :options="options"
        @selectChange="selectChange"
      />
      <Pagination
        v-show="total > 0"
        :total="total"
        :pageNo.sync="listQuery.pageNo"
        :pageSize.sync="listQuery.pageSize"
        @pagination="getInvoiceList"
      />
      <!-- 数据表格 end -->
    </el-card>
  </div>
</template>

<script>
import { mapState, mapMutations } from 'vuex'
import { export2Excel } from '@/utils/export'
import { INVOICE_STATUS } from '@/enum/user'
export default {
  name: 'CompanyInfoInvoiceLog',
  components: {},
  props: {},
  data() {
    return {
      // 表单搜索配置
      formOption: {
        items: [
          {
            type: 'daterange',
            label: '充值时间',
            value: 'time',
            valueFormat: 'yyyy-MM-dd HH:mm:ss'
          },
          {
            type: 'select',
            label: '开票状态',
            value: 'status',
            selectList: [
              { label: '全部', value: '' },
              { label: '已开票', value: '2' },
              { label: '未开票', value: '1' }
            ],
            clear: () => {
              // this.getList()
            }
          }
        ],
        formData: {}
      },
      // 表单按钮列表
      btnList: [
        {
          type: 'primary',
          label: '搜索',
          onClick: () => {
            this.listQuery.pageNo = 1
            this.getInvoiceList()
          }
        },
        {
          label: '导出',
          onClick: () => {
            this.exportFile()
          }
        }
      ],

      // 分页配置
      listQuery: {
        pageNo: 1,
        pageSize: 10
      },
      total: 0,

      // 表格加载
      loading: true,
      // 表格配置
      options: {
        border: true,
        select: true
      },
      // 表格列配置
      columns: [
        { prop: 'invoiceTitle', label: '发票抬头' },
        { prop: 'invoiceTfn', label: '发票税号' },
        {
          label: '内容/金额',
          render: (h, { row }) => {
            return (
              <div>
                <p>{row.content}</p>
                <p>￥{row.cashAmount}</p>
              </div>
            )
          }
        },
        { prop: 'receiveTarget', label: '电子邮箱' },
        {
          label: '银行卡信息',
          prop: 'bankAddress',
          render: (h, { row }) => {
            return (
              <div>
                <p>{row.bankAddress}</p>
                <p>{row.bankAccount}</p>
              </div>
            )
          }
        },
        { prop: 'address', label: '注册地址' },
        { prop: 'orderNo', label: '开票单号' },
        {
          label: '开票状态',
          prop: 'status',
          render: (h, { row }) => {
            const typeTextObj = {
              1: '新申请',
              2: '已开票'
            }
            // const btnTextObj = {
            //   1: '去处理',
            //   2: '查看记录'
            // }
            const typeColorObj = {
              1: '#fc4560',
              2: '#333'
            }
            return (
              <div>
                <p style={`color:${typeColorObj[row.status]}`}>{typeTextObj[row.status]}</p>
                {row.status === 1 ? (
                  <p style="color:#409eff;cursor: pointer;" onClick={() => this.toHandle(row)}>
                    去处理
                  </p>
                ) : (
                  <el-popover placement="left" title="开票记录" width="400" trigger="click">
                    <div style="padding:10px;border-bottom:1px solid #eee">
                      <div class="flex">
                        <h4>凭证：</h4>
                        <el-image
                          style="width: 100px; height: 100px"
                          src={row.voucher}
                          preview-src-list={[row.voucher]}
                        ></el-image>
                      </div>
                      <div class="flex mt-5">
                        <h4 style="flex-shrink:0;">备注：</h4>
                        <p>{row.remark || '暂无'}</p>
                      </div>
                    </div>
                    <div class="flex mt-5 justify-between">
                      <p>操作员：{row.auditUser}</p>
                      <p class="ml-10">时间：{row.auditTime}</p>
                    </div>
                    <p style="color:#2a94f4;cursor: pointer;" slot="reference">
                      查看理由
                    </p>
                  </el-popover>
                )}
              </div>
            )
          }
        },
        { prop: 'createdTime', label: '申请时间' }
      ],
      // 表格源数据
      dataSource: [],
      // 勾选行
      selectList: []
    }
  },
  computed: {
    // 企业主资料刷新开票记录列表
    ...mapState('base', ['etpRefreshInvocieLog'])
  },
  watch: {
    // 监听企业主资料刷新开票记录列表
    etpRefreshInvocieLog: {
      async handler(newValue) {
        if (newValue) {
          await this.getInvoiceList()
          this.SET_INVOCIE_LOG(false)
        }
      }
    }
  },
  created() {
    // 获取开票记录列表
    this.getInvoiceList()
  },
  mounted() {},
  methods: {
    ...mapMutations('base', ['SET_INVOCIE_LOG']),
    // 获取开票记录列表
    async getInvoiceList() {
      try {
        // 参数整理
        const params = {
          ...this.listQuery,
          etpId: this.$route.query.id,
          status: this.formOption.formData.status,
          startTime: this.formOption.formData?.time?.[0] ?? '',
          endTime: this.formOption.formData?.time?.[1] ?? ''
        }
        // 发送请求
        const {
          data: { records, total }
        } = await this.$http.user.etpInvoiceRecord.list({ params })
        // console.log(records, total)
        this.dataSource = records
        this.total = total
        this.loading = false
      } catch (error) {
        console.log('getInvoiceList', error)
      }
    },

    /**
     * 勾选列表行数据
     * @parma {Array} rows 选中行
     */
    selectChange(rows) {
      this.selectList = rows
    },

    // 导出表格
    exportFile() {
      if (!this.selectList.length) return this.$message.error('请选择要导出的数据')
      // 表头设置
      const headerData = this.columns.filter(item => item.prop).map(item => item.label)

      headerData.splice(2, 0, '内容')
      headerData.splice(3, 0, '金额')

      // 表格数据字段
      const filterData = this.columns.filter(item => item.prop).map(item => item.prop)
      filterData.splice(2, 0, 'content')
      filterData.splice(3, 0, 'cashAmount')

      // 表格数据
      const tableData = this.selectList.map(item => {
        return {
          ...item,
          content: item.content,
          cashAmount: `￥${item.cashAmount}`,
          bankAddress: `${item.bankAddress || '无'}  ${item.bankAccount || '无'}`,
          status: INVOICE_STATUS[item.status]
        }
      })
      export2Excel(headerData, tableData, filterData, '用户开票记录', () => {
        this.$message.success('导出成功')
      })
    },

    /**
     * 点击去处理
     * @param {Object} row 当前行数据
     */
    toHandle({ id }) {
      this.$emit('changeInvoice', id)
    }
  }
}
</script>

<style lang="scss" scoped></style>
